package com.hethongviet.doorcontrollercall.page;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.hethongviet.preventingmachine.R;
import com.hethongviet.preventingmachine.Utils;
import com.hethongviet.preventingmachine.helps.dialog.DialogMessageBack;
import com.hethongviet.preventingmachine.models.Client;

public class PageChangeContactActivity extends Activity
{
	public static final String EXTRA_CLIENT = "client";
	public static final int REQUEST_ADD = 0;
	public static final int REQUEST_EDIT = 1;
	public static final int REQUEST_ADD_CONTACT_PHONE = 1;

	private String _newName = null;

	private String _newNumber = null;

	private Client client = null;
	private EditText editTextName = null;
	private EditText editTextNumber = null;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		Utils.prepareWindow(this);

		setContentView(R.layout.page_change_contact);

		editTextName = (EditText) findViewById(R.id.change_contact_name_edit_text);
		editTextNumber = (EditText) findViewById(R.id.change_contact_number_edit_text);
		TextView textViewTitle = (TextView) findViewById(R.id.change_contact_title);

		if (getIntent().getExtras() != null)
		{
			client = (Client) getIntent().getExtras().getSerializable(
					EXTRA_CLIENT);
			textViewTitle.setText(R.string.contact_edit);
			editTextName.setText(client.getDeviceName());
			editTextNumber.setText(client.getDeviceNumber());
		}
		else
		{
			textViewTitle.setText(R.string.contact_add);
		}

		final Button buttonAccept = (Button) findViewById(R.id.change_button_accept);
		final Button buttonCancel = (Button) findViewById(R.id.change_button_cancel);

		buttonAccept.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				_newName = editTextName.getText().toString().trim();
				if (TextUtils.isEmpty(_newName))
				{
					showDialogWithCatch(R.string.message_error_input_null);
					return;
				}

				for (int index = 0; index < _newName.length(); index++)
				{
					char c = _newName.charAt(index);

					if (!Character.isLetterOrDigit(c) && c != '_' && c != '-'
							&& c != ' ')
					{
						showDialogWithCatch(R.string.message_error_wrong_input_name);
						return;
					}
				}

				// if (client != null &&
				// _newName.equals(client.getDeviceName()))
				// {
				// showDialogWithCatch(R.string.message_error_input_name_same_old);
				// return;
				// }

				_newNumber = editTextNumber.getText().toString().trim();
				if (TextUtils.isEmpty(_newNumber))
				{
					showDialogWithCatch(R.string.message_error_input_null);
					return;
				}

				// if (client != null
				// && _newNumber.equals(client.getDeviceNumber()))
				// {
				// showDialogWithCatch(R.string.message_error_input_number_same_old);
				// return;
				// }

				if (client == null)
				{
					client = new Client();
				}

				client.setDeviceName(_newName);
				client.setDeviceNumber(_newNumber);

				/* Save */
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				bundle.putSerializable(EXTRA_CLIENT, client);
				intent.putExtras(bundle);
				setResult(RESULT_OK, intent);
				finish();
			}
		});
		buttonCancel.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				setResult(RESULT_CANCELED);
				finish();
			}
		});
	}

	private void showDialogWithCatch(int id)
	{
		try
		{
			showDialog(id);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		menu.clear();
		if (getIntent().getExtras() == null)
		{
			getMenuInflater().inflate(R.menu.add_contact, menu);
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		if (item.getItemId() == R.id.menu_add_from_phone_contact)
		{
			// Intent intent = new Intent(PageChangeContactActivity.this,
			// ContactListActivity.class);
			// startActivityForResult(intent,
			// PageChangeContactActivity.REQUEST_ADD_CONTACT_PHONE);

			// Intent intent = new Intent(Intent.ACTION_PICK);
			// intent.setType(CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
			//
			// Intent intent = new Intent(Intent.ACTION_PICK,
			// Phones.CONTENT_URI);

			// Intent intent = new Intent(Intent.ACTION_PICK,
			// PhoneLookup.CONTENT_FILTER_URI);
			// intent.setType(Phones.CONTENT_TYPE);
			//

			Intent intent = new Intent(Intent.ACTION_PICK,
					ContactsContract.Contacts.CONTENT_URI);

			startActivityForResult(intent, 1);
		}
		return true;
	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		return new DialogMessageBack(this, true, id, false);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (resultCode == RESULT_OK)
		{
			if (data != null)
			{
				Uri uri = data.getData();
				Cursor cursor = getContentResolver().query(
						uri,
						new String[] { ContactsContract.Contacts.DISPLAY_NAME,
								ContactsContract.Contacts._ID,
								ContactsContract.Contacts.HAS_PHONE_NUMBER },
						null, null, null);

				if (cursor != null && cursor.moveToFirst())
				{
					/******************** 1 *********************/
					// editTextName.setText(cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME)));
					// editTextNumber.setText(cursor.getString(cursor.getColumnIndex(PhoneLookup.NUMBER)));

					/********************** 2 *******************/
					// editTextName.setText(cursor.getString(cursor.getColumnIndex(CommonDataKinds.Phone.DISPLAY_NAME)));
					// editTextNumber.setText(cursor.getString(cursor.getColumnIndex(CommonDataKinds.Phone.NUMBER)));

					/*********************** 3 ******************/
					editTextName.setText(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));

					String id = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID));

					String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
					editTextNumber.setText("");
					if (hasPhone.equalsIgnoreCase("1"))
					{
						Cursor phones = getContentResolver().query(
								ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
								null,
								ContactsContract.CommonDataKinds.Phone.CONTACT_ID
										+ " = " + id, null, null);
						phones.moveToFirst();
						editTextNumber.setText(phones.getString(phones.getColumnIndex("data1")));

					}

				}

			}
		}
	}
}
